package com.dayu.controller;

import com.dayu.model.ArticleCategoryModel;
import com.dayu.service.IArticleCategoryService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by dayu on 2017/4/26 0026.
 * Email：yzjs@qq.com
 */
@Controller
@RequestMapping("article-category")
public class ArticleCategoryController {

    @Autowired
    private IArticleCategoryService iArticleCategoryService;

    /**
     * 1. 使用RequestMapping注解来映射请求的URL，这里匹配的请求路径是“http://localhost:8080/hello。
     * 2. 返回值会通过视图解析器解析为实际的物理视图, 对于InternalResourceViewResolver视图解析器，会做如下解析： 通过prefix+returnVal+suffix 这样的方式得到实际的物理视图。
     * 3. RequestMapping可限制请求方式（GET、POST、PUT、DELETE等），比如用户留言，我们可只允许POST提交：@RequestMapping("/subMessage",method=RequestMethod.POST)。
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String listView(Model model, HttpServletRequest request, HttpServletResponse response) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        model.addAttribute("path", path);
        model.addAttribute("basePath", basePath);
        List<ArticleCategoryModel> list = iArticleCategoryService.getAll();
        model.addAttribute("articleCategoryModels", list);
        return "article-category/list";
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public String create(HttpServletRequest request, HttpServletResponse response) {
        try {
//            request.setCharacterEncoding("UTF-8");
            String name = request.getParameter("name");
            if (name != null && name.length() > 0) {
                ArticleCategoryModel articleCategoryModel = new ArticleCategoryModel();
                articleCategoryModel.setName(name);
                int result = iArticleCategoryService.insert(articleCategoryModel);
                if (result > 0) {
                    return "success";
                }
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "error";
    }

    @RequestMapping(value = "delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String delete(@PathVariable(value = "id") Integer id) {
        int k = iArticleCategoryService.deleteById(id);
        return k > 0 ? "success" : "error";
    }

    @RequestMapping(value = "{id}", method = RequestMethod.GET)
    @ResponseBody
    public String get(@PathVariable(value = "id") Integer id) {
        if (id != null && id > 0) {
            ArticleCategoryModel articleCategoryModel = iArticleCategoryService.getModelById(id);
            ObjectMapper mapper = new ObjectMapper();
            try {
                String json = mapper.writeValueAsString(articleCategoryModel);
                return json;
            } catch (JsonProcessingException ex) {
                return String.format("{error:'%s'}", ex.getMessage());
            }
        }
        return String.format("{error:'%s'}", "没有找到数据");
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public String update(HttpServletRequest request, HttpServletResponse response) {
        try {
            String name = request.getParameter("name");
            String idStr = request.getParameter("id");
            ArticleCategoryModel articleCategoryModel = new ArticleCategoryModel();
            if (idStr != null && idStr.length() > 0) {
                articleCategoryModel.setId(Integer.valueOf(idStr));
            }
            if (name != null && name.length() > 0) {
                articleCategoryModel.setName(name);
            }
            if (articleCategoryModel.getId() > 0 && articleCategoryModel.getName() != null
                    && articleCategoryModel.getName().length() > 0) {
                int result = iArticleCategoryService.update(articleCategoryModel);
                if (result > 0) {
                    return "success";
                }
            }
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "error";
    }

}
